#!/bin/bash
#autoSetup tool 

# arg1 deviceURI
# arg2 ppd path

function db ()
{
  >&2 echo "DEBUG: commandtodnp: $@"
}

dnp_renameQueue ()
{
  local -i try=$2
# rename "Dai Nippon Printing" to "DNP"
#db "looking for old-style queue names ..."
qs=($(lpstat -v |awk -v uri="${1}" '{if($NF == uri){sub(":","",$3);print $3}}'))
for q in "${qs[@]}";do
  D=$(lpstat -l -p ${q}|awk '/Description: / {sub("[\t ]*Description:[\t ]*","",$0);print $0}')
  newD="${D/Dai Nippon Printing/DNP}"
  ((try=0))
  if test "${D}" != "${newD}"; then
    db "found a q in ${q} ... updating $D to $newD"
    lpadmin -p ${q} -D "${newD}"
    echo -e '#CUPS-COMMAND\nAutoConfigure\n'|lp -d ${q} -- - >/dev/null
  fi
done
if ((try));then
  db "autoSetup $1 will try $((try--)) more times"
  $(sleep $((5-try));dnp_renameQueue "${1}" ${try})&
fi
}

dnp_fixDeviceURI ()
{
# a bug in some versions of Mac OS X starting with 10.9.4
# causes the printer queues to be inappropriately "disabled"
# at unexpected times. The bug is revealed with these printers
# due to their lack of USB serial numbers
# a workaround is to modify the deviceURI to eliminate the spurious
# serial# component

V=$1
newV=${V/?serial=%09/}
test "$V" = "${newV}" && return

# find all queues corresponding to this device URI and fix them
qs=($(lpstat -v |awk -v uri="${V}" '{if($NF == uri){sub(":","",$3);print $3}}'))
for q in "${qs[@]}";do
  db "found queue \"${q}\" ... updating deviceURI from $V to $newV"
  lpadmin -p ${q} -v "${newV}"
done

}

PPD="${2}"

dnp_fixDeviceURI "${1}"

$(sleep 1;dnp_renameQueue "${1}" 5)&

test -r "${PPD}" || exit 1
cat "${PPD}"
#awk '/^[*]([a-z]{2}|zh-Hans)[.](PageSize|cupsIPPReason) / {print $0;next};/^[*]([a-z]{2}|zh-Hans)[.].+ / {next}; /./ {print $0}' "${PPD}"
exit
